package com.xuebank.nfe.nfecar.view

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Looper
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.view.Display
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast

import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.wzn.libaray.utils.Logger
import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.wzn.libaray.utils.toast.ToastHelper
import com.xuebank.nfe.nfecar.MainActivity
import com.xuebank.nfe.nfecar.MainActivity.Companion.wx_api
import com.xuebank.nfe.nfecar.R
import com.xuebank.nfe.nfecar.beas.BaseActivity
import com.xuebank.nfe.nfecar.globals.Constants
import com.xuebank.nfe.nfecar.utils.bridge.CallBackFunction

import org.json.JSONException
import org.json.JSONObject

import java.io.ByteArrayOutputStream
import java.io.File
import java.net.URL


/**
 * Created by admin Mr.WANG 2018/10/30.
 */

class SharePopupWindow(context: BaseActivity, widths: Int, height: Int, send_datas: JSONObject,function: CallBackFunction?) : PopupWindow(context), View.OnClickListener {

    private val mContext: Context? = null
    private var fileName = ""
    private var file: File? = null
    private var iwxapi: IWXAPI? = null

companion object {
   val  function: CallBackFunction? = null
}

    init {

        val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val view = inflater.inflate(R.layout.lay_share, null)
        val weixin = view.findViewById<View>(R.id.tv_wx_session)
        val friend = view.findViewById<View>(R.id.tv_wx_timelie)
        val soucang = view.findViewById<View>(R.id.tv_wx_favorite)
        val dismiss = view.findViewById<View>(R.id.tv_wx_favorite)
        isClippingEnabled = false
        this.contentView = view
        this.width = widths
        this.height = height
        this.isFocusable = true
        val dw = ColorDrawable(-0x50000000)
        this.setBackgroundDrawable(dw)
        var shareTitle: String? = null
        val req = SendMessageToWX.Req()
        iwxapi = WXAPIFactory.createWXAPI(context, Constants.WECHAT_APP_ID, true)
        iwxapi?.registerApp(Constants.WECHAT_APP_ID)
        shareTitle = send_datas.get("title") as String
        val shareContent = send_datas.get("content") as String
        val shareUrlStr = send_datas.get("urlStr") as String
        val shareImageUrl = send_datas.get("imageUrl") as String
        val webPage = WXWebpageObject()
        webPage.webpageUrl = shareUrlStr
        val wxMsg = WXMediaMessage(webPage)
        wxMsg.title = shareTitle
        wxMsg.description = shareContent
        try {


            Thread(Runnable {
                try {
                    val url = URL(shareImageUrl)
                    val thumb = BitmapFactory.decodeStream(url.openStream())
                    val scaledBitmap = Bitmap.createScaledBitmap(thumb, 120, 150, true)
                    wxMsg.thumbData = bmpToByteArray(scaledBitmap, true)
                    req.transaction = System.currentTimeMillis().toString()
                    req.message = wxMsg
                    Looper.prepare()
                    Looper.loop()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }).start()
        } catch (e: JSONException) {
            e.printStackTrace()
        }


        val mOnClickListener = View.OnClickListener { v ->
            if (v.id != R.id.tv_cancel) {
                dismiss()
            }
            if (isWeixinAvilible(context)) {
                when (v.id) {
                    R.id.tv_wx_session -> {
                        req.scene = SendMessageToWX.Req.WXSceneSession
                        wx_api?.sendReq(req)
                    }
                    R.id.tv_wx_timelie -> {
                        req.scene = SendMessageToWX.Req.WXSceneTimeline
                        wx_api?.sendReq(req)
                    }
                    R.id.tv_wx_favorite -> {
                        req.scene = SendMessageToWX.Req.WXSceneFavorite
                        wx_api?.sendReq(req)
                    }
                }
            } else {
                Toast.makeText(context,"请先安装微信",Toast.LENGTH_SHORT).show()
            }
//            function?.onCallBack()

        }


        weixin.setOnClickListener(mOnClickListener)
        friend.setOnClickListener(mOnClickListener)
        soucang.setOnClickListener(mOnClickListener)
        dismiss.setOnClickListener(mOnClickListener)


    }


    override fun onClick(v: View) {

    }




    fun isWeixinAvilible(context: Context): Boolean {
        val packageManager = context.packageManager// 获取packagemanager
        val pinfo = packageManager.getInstalledPackages(0)// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (i in pinfo.indices) {
                val pn = pinfo[i].packageName
                if (pn == "com.tencent.mm") {
                    return true
                }
            }
        }

        return false
    }

    fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray {
        val output = ByteArrayOutputStream()
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output)
        if (needRecycle) {
            bmp.recycle()
        }

        val result = output.toByteArray()
        try {
            output.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return result
    }
}
